package com.ifcreate.infowell.sys.service;

import cn.hutool.core.io.FileUtil;
import com.ifcreate.infowell.common.util.JsonResult;
import com.ifcreate.infowell.common.util.ResourcesProperty;
import com.ifcreate.infowell.common.util.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author PuaChen
 * @Create 2018-07-06 12:50
 */
@Service
public class LocalFileUploadServiceImpl implements FileUploadService {


    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ResourcesProperty resourcesProperty;

    /**
     * 最基础的文件上传
     *
     * @param file
     * @param namePrefix 选择性给值 文件的前缀
     * @return 成功后返回的是文件名称地址 可直接存入数据库的
     */
    @Override
    public JsonResult<UploadResult> upload(MultipartFile file, String namePrefix) {
        if (resourcesProperty == null) {
            throw new NullPointerException("配置文件类没有被初始化");
        }
        if (file == null || file.isEmpty()) {
            return JsonResult.error("参数错误");
        }

        String originalName = file.getOriginalFilename();
        String fileType = originalName.substring(originalName.lastIndexOf("."));
        String newName = UUIDUtils.generateShortUuid();
        if (StringUtils.isNotBlank(namePrefix)) {
            newName = namePrefix + newName;
        }
        newName = newName + fileType;
        File root = new File(resourcesProperty.getDir());
        //如果目录不存在则创建
        if (!root.exists()) {
            root.setWritable(true);
            root.mkdirs();
        }
        File dest = new File(root, newName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            logger.error("保存文件出现异常", e);
            return JsonResult.error("文件上传失败");
        } finally {
            logger.info("文件上传信息：文件名：{},文件路径：{}", newName, dest.getAbsolutePath());
        }
        String url = resourcesProperty.getPrefix();
        if (!url.endsWith("/")) {
            url = url + "/";
        }
        url = url + newName;
        UploadResult uploadResult = new UploadResult();
        uploadResult.setUrl(url);
        uploadResult.setName(newName);
        uploadResult.setOriginalName(originalName);
        uploadResult.setSize(FileUtil.readableFileSize(dest));
        logger.info("文件上传成功,{}", url);
        return JsonResult.success(uploadResult);
    }

    @Override
    public File getRootDir() {
        File root = new File(resourcesProperty.getDir());
        //如果目录不存在则创建
        if (!root.exists()) {
            root.setWritable(true);
            root.mkdirs();
        }
        return root;
    }

    @Override
    public UploadResult getFileInfo(File file) {
        String url = resourcesProperty.getPrefix();
        if (!url.endsWith("/")) {
            url = url + "/";
        }
        url = url + file.getName();
        UploadResult uploadResult = new UploadResult();
        uploadResult.setUrl(url);
        uploadResult.setName(file.getName());
        uploadResult.setSize(FileUtil.readableFileSize(file));
        return uploadResult;
    }
}
